﻿using LogionDemo.Common.Helper.Enums;
using LogionDemo.Models;
using Masuit.Tools.Security;

namespace LogionDemo.Common.Helper
{
	public static class LoginHelper
	{
		/// <summary>
		/// 用户登录
		/// </summary>
		/// <param name="dbContext">数据库模型</param>
		/// <param name="userName">登录名称</param>
		/// <param name="password">登录密码</param>
		/// <param name="action">登录成功后执行</param>
		/// <param name="additionalValidation">附加条件判断</param>
		/// <returns>登录结果</returns>
		public static LoginResult LoginUser(RegisterInfoContext dbContext, string userName, string password, Action<UserToken> action = null, Func<string, string, bool> additionalValidation = null)
		{
			if (string.IsNullOrEmpty(userName))
			{
				return LoginResult.UserNameEmpty;
			}
			if (string.IsNullOrEmpty(password))
			{
				return LoginResult.PasswordEmpty;
			}
			if (additionalValidation != null && !additionalValidation(userName, password))
			{
				return LoginResult.AdditionalValidationFailed;
			}

			var user = dbContext.UserInfos.FirstOrDefault(info => info.UserName == userName);
			if (user == null)
			{
				return LoginResult.UserNotFound;
			}
			var passwordWithSalt = $"{password}{user.PasswordSalt}".SHA256();
			if (string.Equals(user.Password, passwordWithSalt))
			{
				action?.Invoke(new UserToken() { UserName = user.UserName!, Role = user.UserRole });
				return LoginResult.Success;
			}
			else
			{
				return LoginResult.InvalidPassword;
			}
		}

		// 注册新用户
		public static RegisterResult RegisterUser(RegisterInfoContext dbContext, string userName, string password, Func<string, string, bool> additionalValidation = null)
		{
			if (string.IsNullOrEmpty(userName))
			{
				return RegisterResult.UserNameEmpty;
			}
			if (string.IsNullOrEmpty(password))
			{
				return RegisterResult.PasswordEmpty;
			}
			if (additionalValidation != null && !additionalValidation(userName, password))
			{
				return RegisterResult.AdditionalValidationFailed;
			}

			if (dbContext.UserInfos.Any(info => info.UserName == userName))
			{
				return RegisterResult.InvalidUserName;
			}
			string passwordSalt = CryptoHelper.GenerateSalt();
			string passwordSHA256 = $"{password}{passwordSalt}".SHA256();
			UserInfo newUser = new UserInfo
			{
				UserName = userName,
				Password = passwordSHA256,
				PasswordSalt = passwordSalt,
			};
			dbContext.UserInfos.Add(newUser);
			dbContext.SaveChanges();
			return RegisterResult.Success;
		}
	}
}